package com.example.lianjuan.ui.custom;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.example.lianjuan.R;

public class rotateView extends AppCompatImageView {
    private int mDegrees;
    private boolean mNeedRotate;
    private ObjectAnimator mAnimator;

    public rotateView(@NonNull Context context) {
        this(context, null);
    }

    public rotateView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public rotateView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setImageResource(R.mipmap.loading);
        //RotateAnimator();
        startRotate();
    }

    private void startRotate() {

        post(new Runnable() {
            @Override
            public void run() {
                mDegrees += 20;
                if (mDegrees >= 360) {
                    mDegrees = 0;
                }
                //绘制刷新
                invalidate();
                if (getVisibility() == VISIBLE && mNeedRotate) {
                    postDelayed(this, 50);
                } else {
                    removeCallbacks(this);
                }
            }
        });
    }

    @Override
    protected void onAttachedToWindow() {
        mNeedRotate = true;
        super.onAttachedToWindow();
        if (mAnimator != null) {
            mAnimator.start();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        mNeedRotate = false;
        super.onDetachedFromWindow();
        if (mAnimator != null) {
            mAnimator.end();
        }
    }

    //绘制图片旋转
    @Override
    protected void onDraw(Canvas canvas) {
        canvas.rotate(mDegrees, getWidth() / 2, getHeight() / 2);
        super.onDraw(canvas);
    }

    //使用ObjectAnimator旋转
    private void RotateAnimator() {
        //添加旋转动画，旋转中心默认为控件中点
        mAnimator = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f);
        //设置动画时间
        mAnimator.setDuration(1000);
        mAnimator.setInterpolator(new LinearInterpolator());
        //动画时间线性渐变
        mAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        mAnimator.setRepeatMode(ObjectAnimator.RESTART);
    }
}
